<template>
  <!-- 商品列表 -->
  <div class="sort-list-container">
    <ul>
      <li v-for="good in goodList" :key="good.id">
        <GoodsItem :good="good" />
      </li>
    </ul>
  </div>
  <!-- 上拉加载更多 -->
  <XtxInfiniteLoad
    :isLoading="isLoading"
    :isFinished="isFinished"
    @load="getNextPage"
  />
</template>

<script>
import GoodsItem from './goods-item.vue'
import { findSubCategoryGoods } from '@/api/category.js'
import { useRoute } from 'vue-router'
import { ref, watch, inject } from 'vue'
export default {
  components: {
    GoodsItem
  },
  setup () {
    const goodList = ref([])
    const route = useRoute()
    const requestParams = {
      page: 1,
      pageSize: 20,
      categoryId: route.params.id,
      sortField: null,
      attrs: [],
      brandId: null
    }
    // 实现上拉加载更多
    const isLoading = ref(false)
    const isFinished = ref(false)
    // 接收过滤条件数据
    const filterParams = inject('filterParams')
    // 监听filterParams变化，变化刷新列表
    watch(() => filterParams.value, () => {
      console.log('过滤条件变化', filterParams.value)
      // 重置列表
      goodList.value = []
      requestParams.page = 0
      isLoading.value = false
      isFinished.value = false
      // getGoodList()
    }, { deep: true })
    // const getGoodList = async () => {
    //   const { result } = await findSubCategoryGoods({ ...requestParams, ...filterParams.value })
    //   console.log(result)
    //   goodList.value = result.items
    // }
    // 下拉加载更多回调函数
    const getNextPage = async () => {
      /**
       * 开启列表加载，显示loading isLoading = true
       * 发请求获取列表数据
       * 获取到数据后，追加到列表
       * 关闭加载状态 loading = false
       * 判断列表数据是否加载完了 根据list长度和后台total对比，加载完 isFinished = true
       */
      isLoading.value = true
      requestParams.page++
      const { result: { items, counts } } = await findSubCategoryGoods({ ...requestParams, ...filterParams.value })
      goodList.value.push(...items)
      isLoading.value = false
      if (goodList.value.length === counts) {
        isFinished.value = true
      }
    }
    // onMounted(() => {
    //   getGoodList()
    // })
    return { goodList, isLoading, isFinished, getNextPage }
  }
}
</script>

<style lang="less" scoped>
.sort-list-container {
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
